<template>
  <div>
    <PageDialog
      :title="dialogInfo.title"
      v-model:visible="shows"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="dialog-table">
        <PageFilter
          v-model:query="filterInfo.query"
          :filter-list="filterInfo.list"
        >
          <template v-slot:filter-button>
            <div>
              <div class="dialog-table-header">
                <div class="header-left">
                  <div class="lable">产品名称：{{ info.commonName }}</div>
                  <div class="lable">生产批号：{{ info.batchNumber }}</div>
                </div>
                <div class="header-right">
                  <div class="scan-groups">
                    <el-input
                      v-model="filterInfo.keyword"
                      :clearable="true"
                      placeholder="请输入个体码"
                      @keyup.enter.native="search"
                      @input="(e) => (filterInfo.keyword = validSe(e))"
                    ></el-input>
                    <el-button style="margin-left: 10px" @click="search"
                      >搜索</el-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </template>
        </PageFilter>
      </div>
      <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
        <PageTable
          v-model:data="tableInfo.data"
          :check-box="false"
          :tab-index="true"
          :listen-height="false"
          :pager="false"
          :field-list="tableInfo.fieldList"
          :row-class-name="tableRowClassName"
          :handle="tableInfo.handle"
        >
          <template v-slot:col-qty="scope">
            <el-form-item class="margin-bottom">
              <div class="page-table-input-number-wrapper">
                <div class="page-table-input-number-left">
                  <div class="page-table-input-number-item">
                    <el-form-item
                      :prop="`data.${scope.$index}.largeUnitQty`"
                      :rules="scope.$index >= 0 ? [
                        {
                          validator: $validate.positiveAndZero,
                          trigger: 'blur',
                        },
                      ] : []"
                    >
                      <el-input-number
                        v-model.lazy="scope.row.largeUnitQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="
                          scope.row.qtyOperateMode === 0 ||
                          scope.row.qtyOperateMode === 2
                            ? 0
                            : systemConfig.qty_show_precision
                        "
                        :min="0"
                        :max="largeMax(scope.row)"
                        @change="
                          changeLarge(
                            $event,
                            scope.row,
                            `data.${scope.$index}.largeUnitQty`
                          )
                        "
                      />
                    </el-form-item>
                    <div class="page-table-input-number-item-unite">
                      {{ scope.row.unitName }}
                    </div>
                  </div>
                  <div
                    v-if="
                      scope.row.unitConvertCoefficient > 1 &&
                      scope.row.qtyOperateMode === 2
                    "
                    class="page-table-input-number-item"
                  >
                    <el-form-item>
                      <el-input-number
                        v-model.lazy="scope.row.smallUnitQty"
                        style="width: 100%; margintop: 18px"
                        clearable
                        controls-position="right"
                        :precision="0"
                        :min="0"
                        :max="smallMax(scope.row)"
                        @change="changeSmall($event, scope.row)"
                      />
                    </el-form-item>
                    <div class="page-table-input-number-item-unite">
                      {{ scope.row.calcUnitName }}
                    </div>
                  </div>
                </div>
                <div
                  v-if="scope.row.qtyOperateMode === 2"
                  class="page-table-input-number-right"
                >
                  {{ $fn.qtyFormatter(scope.row.qty) }}
                </div>
              </div>
            </el-form-item>
          </template>
        </PageTable>
      </el-form>
    </PageDialog>
  </div>
</template>

<script setup name="IndividualDetails">
const { proxy } = getCurrentInstance()
const props = defineProps({
  showDialog: {
    type: Boolean,
  },
  pageStatus: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
const scanInput = ref('')
// 过滤相关配置
const systemConfig = ref(proxy.$store.state.permission.systemConfig)
const filterInfo = ref({
  keyword: '',
  list: [{ type: 'slot', value: 'button' }],
})
// 表格相关
const tableInfo = ref({
  data: [],
  selections: [],
  copyData: [],
  fieldList: [
    { label: '个体码', value: 'uniqueCode' },
    { label: '原厂码', value: 'factorySubCode' },
    {
      label: '发货数量',
      value: 'qty',
      width: 250,
      type: 'slot',
    },
    {
      label: '单价',
      value: 'price',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
    {
      label: '总金额',
      value: 'sumAmount',
      type: 'column',
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '50',
    btList: [
      {
        label: '删除',
        event: removeProduct,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: true,
      },
    ],
  },
})
// 弹窗相关
const dialogInfo = ref({
  title: '个体操作',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const shows = computed({
  get() {
    return props.showDialog
  },
  set(val) {
    proxy.$emit('update:showDialog', val) // 更新父组件shows
  },
})
watch(
  () => tableInfo.value.data,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )

        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        let sumAmount = proxy.$fn.accMul(row.qty, row.price || 0)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row['sumAmount'] = sumAmount
      })
    }
  },
  { deep: true }
)
watch(
  () => tableInfo.value.copyData,
  (val) => {
    if (val.length) {
      val.forEach((row) => {
        let smallUnitQty = parseFloat(row.smallUnitQty || 0)
        let unitConvertCoefficient = parseFloat(row.unitConvertCoefficient || 1)
        let largeUnitQty = parseFloat(row.largeUnitQty || 0)
        let calcQty = proxy.$fn.accAdd(
          proxy.$fn.accMul(largeUnitQty, unitConvertCoefficient),
          smallUnitQty
        )

        let qty = proxy.$fn.accDiv(calcQty, unitConvertCoefficient)
        let sumAmount = proxy.$fn.accMul(row.qty, row.price || 0)
        row['calcQty'] = calcQty
        row['qty'] = qty
        row['sumAmount'] = sumAmount
      })
    }
  },
  { deep: true }
)

function tableRowClassName({ row = undefined }) {
  if (row.isChioce) {
    return 'success-row'
  } else {
    return ''
  }
}
function largeMax(row) {
  if (row.qtyOperateMode === 2) {
    if (row.codeType === 3) {
      return 1
    }
    return parseInt(row.deliverableCalcQty / row.unitConvertCoefficient)
  } else {
    if (row.codeType === 3) {
      return 1
    }
    return row.deliverableQty
  }
}
function changeSmall(e, row) {
  let item = tableInfo.value.copyData.find(
    (item) => item.tableIndex === row.tableIndex
  )
  item.smallUnitQty = e
  if (row.codeType === 3 && row.qtyOperateMode === 2) {
    if (e > 0) {
      row.largeUnitQty = 0
      item.largeUnitQty = 0
    }
  }
}
function smallMax(row) {
  let largeUnitQty = parseInt(
    row.deliverableCalcQty / row.unitConvertCoefficient
  )
  if (largeUnitQty === 0 || row.largeUnitQty === largeUnitQty) {
    return parseInt(row.deliverableCalcQty % row.unitConvertCoefficient)
  } else {
    return row.unitConvertCoefficient - 1
  }
}
function changeLarge(e, row, str) {
  proxy.$refs.tableForm.clearValidate(str)
  let item = tableInfo.value.copyData.find(
    (item) => item.tableIndex === row.tableIndex
  )
  item.largeUnitQty = e
  if (row.codeType === 3) {
    if (e === 1) {
      row.smallUnitQty = 0
      item.smallUnitQty = 0
    }
  } else {
    let largeUnitQty = parseInt(
      row.deliverableCalcQty / row.unitConvertCoefficient
    )
    if (row.qtyOperateMode === 2 && row.unitConvertCoefficient > 1) {
      if (largeUnitQty > 0 && e === largeUnitQty) {
        let smallUnitQty = parseInt(
          row.deliverableCalcQty % row.unitConvertCoefficient
        )
        if (row.smallUnitQty > smallUnitQty) {
          row.smallUnitQty = smallUnitQty
          item.smallUnitQty = smallUnitQty
        }
      }
    }
  }
}
function search() {
  const search = filterInfo.value.keyword
  if (search) {
    tableInfo.value.data = tableInfo.value.copyData.filter((data) => {
      return Object.keys(data).some((key) => {
        if (key === 'qrCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'uniqueCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factorySubCode') {
          return String(data[key]).indexOf(search) > -1
        } else if (key === 'factoryMainCode') {
          return String(data[key]).indexOf(search) > -1
        }
      })
    })
  } else {
    tableInfo.value.data = tableInfo.value.copyData
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
}
function handleSave() {
  proxy.$emit('individualBack', tableInfo.value.copyData)
  handleClose()
}
function removeProduct(row) {
  tableInfo.value.data = tableInfo.value.data.filter((item) => item !== row)
  tableInfo.value.copyData = tableInfo.value.copyData.filter(
    (item) => item.tableIndex !== row.tableIndex
  )
}

onMounted(() => {
  let details = proxy.$fn.deepClone(props.info.details)
  details.forEach((item, index) => {
    item.tableIndex = index + 1
  })
  tableInfo.value.data = details
  tableInfo.value.copyData = proxy.$fn.deepClone(details)
})
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.scan-groups {
  display: flex !important;
  align-items: center;
}
</style>
